package com.glwan.fixedassetapp.ui.home.Activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.OfflineAdapter;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.common.ApiConstant;
import com.glwan.fixedassetapp.model.ApiResponse;
import com.glwan.fixedassetapp.model.Asset;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.GsonUtil;
import com.glwan.fixedassetapp.utils.MMKVKeys;
import com.glwan.fixedassetapp.utils.MMKVSingleton;
import com.glwan.fixedassetapp.utils.OkHttpUtil;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ProductActivity extends AppCompatActivity {

    private List<Asset> parentList = new ArrayList<>();


    private ListView listView;

    private OfflineAdapter listableAdapter;
    private int totalPage;
    private int currentPage = 1;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (message.what == 1) {
                pullLoading.setVisibility(View.GONE);

                if (totalPage > 0)
                    noMoreData.setVisibility(View.GONE);
                else
                    noMoreData.setVisibility(View.VISIBLE);

                listableAdapter.setAssetList(parentList);
                currentPage++;
                return true;
            } else {
                return false;
            }
        }
    });

    private LinearLayout pullLoading;

    private LinearLayout noMoreData;
    private View loadingMore;

    private Activity getActivity() {
        return this;
    }    //列表

    private void initData() {
        listView = findViewById(R.id.listView);
        listableAdapter = new OfflineAdapter(getActivity());
        listView.setAdapter(listableAdapter);
        loadingMore = LayoutInflater.from(getActivity()).inflate(R.layout.loading_more, null);
        pullLoading = loadingMore.findViewById(R.id.pullLoading);
        noMoreData = loadingMore.findViewById(R.id.noMoreData);

        listView.addFooterView(loadingMore, null, false);

        pullLoading.setVisibility(View.VISIBLE);
        listView.setOnItemLongClickListener((parent, view, position, id) -> {
            Map<String, Object> selectMap = new HashMap<>();
            Asset item = listableAdapter.getItem(position);
            selectMap.put("fdId", item.getId());
            CommonUtil.intentConfirmDialog(
                    getActivity(),
                    InventoryTaskScanningActivity.class,
                    R.drawable.question,
                    getString(R.string.confirmInvetoryScan),
                    getString(R.string.confirm),
                    getString(R.string.cancel),
                    selectMap,
                    false);

            return true;
        });

        //请求后台数据
        currentPage = 1;
        getDataNew();

    }

    Callback kmAssetApplyTaskCallback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            CommonUtil.toastShow(getActivity(), e.getMessage(), CommonUtil.ERROR, true);
            setScrollListener(true);
            //关闭加载框
            CommonUtil.cancelProgressDialog(getActivity());
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            ApiResponse<List<Asset>> responseData = GsonUtil.fromJson(response, new TypeToken<ApiResponse<List<Asset>>>() {
            }.getType());


            if (responseData != null && responseData.isSuccess()) {
                totalPage = responseData.getPageCount();
                parentList.addAll(responseData.getData());
                Message msg = new Message();
                msg.what = 1;
                handler.sendMessage(msg);
            } else {
                String msg;
                if (responseData == null || responseData.getMsg() == null) {
                    msg = "请求失败";
                } else {
                    msg = responseData.getMsg();
                }
                CommonUtil.toastShow(getActivity(), msg, CommonUtil.ERROR, true);
            }
            //关闭加载框
            setScrollListener(true);
            CommonUtil.cancelProgressDialog(getActivity());

        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home_product);
        setTitle(getString(R.string.product_list));

        Toolbar toolbar = findViewById(R.id.moreToolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        initData();
    }


    private void setScrollListener(boolean open) {
        if (open) {
            listView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                        if (view.getLastVisiblePosition() == parentList.size()) {
                            if (currentPage >= totalPage) {
                                pullLoading.setVisibility(View.GONE);
                                noMoreData.setVisibility(View.VISIBLE);
                                Log.i("currentPage！！！", String.valueOf(currentPage));

                            } else {
                                pullLoading.setVisibility(View.VISIBLE);
                                noMoreData.setVisibility(View.GONE);
                                setScrollListener(false);
                                getDataNew();
                            }
                        }

                    }
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                }
            });
        } else {
            listView.setOnScrollListener(null);
        }
    }

    /**
     * 获取数据
     */
    private void getDataNew() {
        //打开加载框
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));

        //获取服务地址和session
        String session = MMKVSingleton.getString(MMKVKeys.KEY_SESSION, "");
        String address = MMKVSingleton.getString(MMKVKeys.KEY_DOMAIN, "");
        String GET_TASK_LIST_URL = address + ApiConstant.GET_TASK_LIST_NEW + "?method=getList&pageNo=" + currentPage;

        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("Cookie", "SESSION=" + session);

        //获取列表
        OkHttpUtil.postNew(GET_TASK_LIST_URL, "text/plain", headerMap, null, kmAssetApplyTaskCallback);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }


}

